//
//  ZYXNSURLConnectionSecurePOSTViewController.m
//  Internet
//  NSURLConnection POST Secure
//

#import "ZYXNSURLConnectionSecurePOSTViewController.h"
#import "MBProgressHUD+MJ.h"
#import "NSString+Hash.h"

@interface ZYXNSURLConnectionSecurePOSTViewController ()

@property (weak, nonatomic) IBOutlet UITextField *usernameField;
@property (weak, nonatomic) IBOutlet UITextField *pwdField;

- (IBAction)loginSecure;

@end

@implementation ZYXNSURLConnectionSecurePOSTViewController

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}



- (IBAction)loginSecure
{

    NSString *username = self.usernameField.text;
    if (username.length == 0) {
        [MBProgressHUD showError:@"请输入用户名"];
        return;
    }
    
    NSString *pwd = self.pwdField.text;
    if (pwd.length == 0) {
        [MBProgressHUD showError:@"请输入密码"];
        return;
    }
    

    [MBProgressHUD showMessage:@"正在拼命加载中..."];
    

    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1:8080/MJServer/login"];
    

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.timeoutInterval = 5;
    request.HTTPMethod = @"POST";
    
  
    [request setValue:@"iOS8.1模拟器" forHTTPHeaderField:@"User-Agent"];
    
#warning 使用MD5加密
    
    pwd = [[pwd stringByAppendingString:@"abcdefg"] md5String]; // 进行MD5加密
    NSLog(@"%@",pwd);
    
    NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@", username, pwd];
    request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
    
    
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        [MBProgressHUD hideHUD];
        
        /** 解析data :
         {"error":"用户名不存在"}
         {"error":"密码不正确"}
         {"success":"登录成功"}
         */
        if (data) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSString *error = dict[@"error"];
            if (error) {
                [MBProgressHUD showError:error];
            } else {
                NSString *success =  dict[@"success"];
                [MBProgressHUD showSuccess:success];
            }
        } else {
            [MBProgressHUD showError:@"网络繁忙, 请稍后再试"];
        }
    }];
}

@end


